#!/bin/sh
echo "lmdprogress:2"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/install_node.sh"
echo "lmdprogress:15"
export CURRENT_APP_PATH="${LMD_APPS_DIR}/SillyTavern"
echo $CURRENT_APP_PATH
mkdir -p "$CURRENT_APP_PATH"

if [ -d "$CURRENT_APP_PATH" ]; then
  echo "App Dir: "$CURRENT_APP_PATH
else
  echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
  exit 1
fi

source "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/sillytavern/env"
export GIT_HOST=${GITHUB_PROXY}"https://github.com"

echo "lmdprogress:20"

if [ -n "$GITHUB_PROXY" ]; then
  # if GITHUB_PROXY value exist, use npm mirror.
  NPM_MIRROR_PARAM="--registry=https://registry.npmmirror.com"
  echo "use npm mirror "$NPM_MIRROR_PARAM
fi
npm -v
node -v

echo "lmdprogress:25"
export GIT_REPO_URL=${GIT_HOST}/SillyTavern/SillyTavern


export GIT_REPO_BRANCH="release"
export LOCAL_REPO_PATH="$CURRENT_APP_PATH"
sh "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/git_clone_and_fetch.sh"

echo "lmdprogress:50"

NPM_CACHE_PARAM="--cache ${LMD_DATA_ROOT}/install-cache/npm"
export NODE_OPTIONS=--max-old-space-size=4096

cd "${CURRENT_APP_PATH}"

echo "npm cache: $NPM_CACHE_PARAM"
npm i $NPM_MIRROR_PARAM $NPM_CACHE_PARAM

echo "lmdprogress:80"

exit_code=$?
if [ $exit_code -eq 190 ]; then
  echo "remove node_modules and reinstall"
  rm -rf ./node_modules
  npm i $NPM_MIRROR_PARAM $NPM_CACHE_PARAM
fi
echo "lmdprogress:95"

if [ $exit_code -ne 0 ]; then
  echo "exit_code: "$exit_code
  exit 1
fi

if [ -n "$_INSTALL_SUCCESS_LOG" ]; then
    echo $_INSTALL_SUCCESS_LOG
fi


# echo "lmd_cmd:auto_start_app"
echo "lmdprogress:100"